#include "epoll.hpp"
class Epoll_Sever
{
public:
    Epoll_Sever()
    {
        _sock = _sever.create();
        // 设置非阻塞
        if (!setblock(_sock))
            cout << "setblock fail..." << endl;
        // 设置端口复用
        int opt = 1;
        setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        _sever.Bind();
        _sever.Listen();
        // 创建epoll模型
        _epoll.Epoll_Create();
        _epoll.Epoll_Ctl(EPOLL_CTL_ADD, _sock, EPOLLIN | EPOLLET);
        // 建立映射关系
        Data_buffer *ptr = new Data_buffer;
        ptr->_sock = _sock;
        ptr->_epfd_ptr = &_epoll;
        ptr->_sock_ptr = &_sever;
        _buffer.emplace(std::make_pair(_sock, ptr));
    }
    void Start()
    {
        epoll_event events[EPOLL_WAIT_NUM];
        memset(events, 0, EPOLL_WAIT_NUM);
        while (true)
        {
            int num = _epoll.Epoll_Wait(events, EPOLL_WAIT_NUM, TIMEOUT);
            switch (num)
            {
            case 0:
                cout << "timeout" << endl;
                break;
            case -1:
                cout << strerror(errno) << endl;
                break;
            default:
                Handle(num, &_buffer, events);
                break;
            }
        }
    }
    ~Epoll_Sever()
    {
        // 释放没有释放的内存，防止野指针的出现或者是内存泄露
        for (auto &e : _buffer)
        {
            if (e.second)
            {
                delete e.second;
                // 防止野指针
                e.second = nullptr;
            }
            if (_sock > 0)
                close(_sock);
        }
    }

private:
    int _sock;
    Epoll _epoll;
    Sock _sever;
    std::unordered_map<int, Data_buffer *> _buffer;
};